import json
from flask import Blueprint, jsonify, make_response, redirect
from db import db
import datetime
import random
import redis
from flask import current_app as app, request
from flask_restful import reqparse
from utils.captcha.captcha import captcha
from utils.myrly import send_message
from utils.myredis import MyRedis,r
from utils.myjwt import MyJwt, myjwt
import requests
import time

user_blue = Blueprint('user', __name__)


@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S') + "   " + request.path + "   error"
    app.logger.error(str)
    app.logger.info('info log')
    app.logger.warning('warning log')

    sql = "insert into user values(0,'aa22222','abc')"
    db.update(sql)
    db.commit()
    sql1 = "select * from user"
    res = db.find_all(sql1)
    print(res)
    return 'ok234234'


# 发送验证码
@user_blue.route("/sendcode", methods=["POST"])
def sendcode():
    # 获取手机号
    req = reqparse.RequestParser()
    req.add_argument('mobile')
    args = req.parse_args()
    mobile = args['mobile']

    if not all([mobile]):
        return jsonify({
            'code': 204,
            'msg': '信息不完整',
        })

    # 2. 生成短信验证码
    smscode = random.randint(100000, 999999)
    # 设置过期时间
    exp = 5
    # 调用封装好的容联云  传参
    res = send_message(mobile, smscode, exp)
    print("res:", res)

    # 将手机号 短信验证码 过期时间存入redis中
    if res:
        rds = redis.Redis(host='localhost', db=6, port=6379)
        rds.set(mobile, smscode, 300)
        return jsonify({'message': '发送成功', 'code': 200, 'smscode': smscode})
    else:
        return jsonify({'msg': '发送失败', 'code': 500})


# 登录
@user_blue.route("/login",methods= ['POST','GET'])
def login():
    req = reqparse.RequestParser()
    req.add_argument('mobile', required=True)
    req.add_argument('code', required=True)
    args = req.parse_args()

    if not all([args['mobile'], args['code']]):
        return jsonify({
            "code": 400,
            "msg": '参数填写完整'
        })
    key = 'sms_%s' % args['mobile']
    rs = MyRedis().get_str(key)
    if not rs:
        return jsonify({
            "code": 400,
            "msg": '验证码过期'
        })
    if rs.decode() != args['code']:
        return jsonify({
            "code": 400,
            "msg": '验证码错误'
        })
    sql = "select * from user where phone='%s'" % args['mobile']
    rs = db.find_all(sql)
    # 没有用户
    if not rs:
        sql = 'insert into user(phone) values (%s,)' % args['mobile']
        db.update(sql)
        db.commit()

    sql = 'select * from user where phone=%s' % args['mobile']
    rs = db.find_all(sql)
    payload = {'data': {
        "id": rs[0]['id'],
        'name': rs[0]['name']
    }}
    token = MyJwt().jwt_encode(payload)
    return jsonify({
        "code": 200,
        "msg": '登录成功',
        "token": token
    })


# 生成图片验证码
@user_blue.route("/create_imagecode")
def create_imagecode():
    # uuid = requests.args.get("uuid")
    name, text, image = captcha.generate_captcha()
    res = make_response(image)
    res.headers['Content-Type'] = "image/jpg"
    # 存入redis
    # r.get_str(uuid,text)；
    return res


@user_blue.route('/get_wb')
def get_weibo():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
    client_id, redirect_uri)
    print(url)
    return jsonify({"url": url})


@user_blue.route('/weiboCallback/')
def weiboCallback():
    # 获取code
    code = request.args.get('code')
    # 通过code去获取uid和token
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    res1 = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    result = json.loads(res1.text)
    uid = result['uid']
    token = result['access_token']
    # 判断数据库是否存在
    sql = "select user.id as uid,user.name as uname from sf_login as sf left join user on sf.userid=user.id where sf.uid='%s'" % (
        uid)
    res = db.find(sql)
    if not res:
        # 不存在绑定用户
        return redirect("http://127.0.0.1:8080/#/binduser?uid=" + uid + "&token=" + token)
    else:
        # 存在获取user
        nowdata = int(time.time())
        data = {'data': {"id": res['uid'], 'name': res['uname'], 'exp': nowdata}}
        token = myjwt.jwt_encode(data)
        # 封装token返回
        return redirect(
            "http://127.0.0.1:8080/#/sflogin?userid=" + str(res['uid']) + "&name=" + res['uname'] + "&token=" + token)


@user_blue.route('/weibobind', methods=['POST'])
def weibobind():
    data = json.loads(request.data)
    # 写入用户表
    sql = "select * from user where phone='%s'" % (data['mobile'])
    user = db.find(sql)
    lastid = user['id']
    if not user:
        insertsql = "insert into user(name,phone) values('%s','%s')" % (data['mobile'], data['mobile'])
        lastid = db.update(insertsql)
    # 查的新写入的id
    # 写入三方登录表
    sansql = "insert into sf_login(userid,u_from,uid,token) values(%d,'%s','%s','%s')" % (
    lastid, 'weibo', data['uid'], data['token'])
    db.update(sansql)
    db.commit()
    # 生成token返回
    nowdata = int(time.time())
    data = {'data': {"id": lastid, 'name': data['mobile'], 'exp': nowdata}}
    token = myjwt.jwt_encode(data)
    return jsonify({"code": 200, "user": {"id": lastid, 'name': data['mobile']}, 'token': token})




